<script setup lang="ts">
  import { uploadAPI } from '@/apis/common';
  import { createRentAPI, deleteEnterpriseAPI, deleteRentAPI, getEnterpriseListAPI, getRentBuildListAPI, getRentListAPI, outRentAPI } from '@/apis/enterprise';
  import type { Enterprise, EnterpriseListParams, RentBuilding, RentItemType, RentParams } from '@/types/enterprise';
  import { dayjs, ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
  import { computed, ref, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';

  // 追加企业类型
  interface EnterprisePlus extends Enterprise {
    rentList: RentItemType[] // 租约列表
  }

  // 获取企业列表所需参数
  const params = ref<EnterpriseListParams>({
    page: 1, // 当前页码
    pageSize:5, // 每页条数
    name: '' // 企业名称
  })

  // 获取企业列表 -----------------
  const exterpriseList = ref<EnterprisePlus[]>([]) // 企业列表
  const total = ref(0) // 总页数
  // 获取企业列表数据
  const getList = async () => {
    const res =  await getEnterpriseListAPI(params.value)
    // 设置数据 添加rentList字段
    exterpriseList.value = res.data.rows.map(item => ({ ...item, rentList: []}))
    total.value = res.data.total
    // 从工作台跳转后的操作
    onRent()
  }

  getList()

  // 搜索 ----------------------------------------------------------------------------
  const onSearch = () => {
    params.value.page = 1 // 重置页码
    getList()  // 重新获取数据
  }

  // 删除企业 -----------------------------------------------------------------------------------
  const deleteEnterprise = async (id: string) => {
    await ElMessageBox.confirm('确定删除该企业吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await deleteEnterpriseAPI(id)
    if(res.code === 10000) {
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
    getList()
  }

  // 添加合同弹窗模块 ----------------------------------------------------------------------------------
  const dialogVisible = ref<boolean>(false) // 弹窗是否显示

  // 开启弹窗 ------------------------
  // 获取楼宇列表
  const buildList = ref<RentBuilding[]>([]) // 楼宇列表
  const dialogType = ref<number>(0) // 弹窗类型，0是添加合同，1是续签合同
  const buildingName = ref<string>('') // 楼宇名称
  // 没有scodeId的参数，则表示是续费合同，否则是添加合同
  const openDialog = async (id: number, scopeId?: number) => {
    dialogVisible.value = true // 显示弹窗
    if (!scopeId) {
      // 添加合同
      dialogType.value = 0
      rentForm.value.type = 0 // 设置操作类型，0添加，1续签
      // 获取楼宇列表
      const res = await getRentBuildListAPI()
      buildList.value = res.data

      // 保存企业id
      rentForm.value.enterpriseId = id
    } else {
      // 续费合同
      dialogType.value = 1
      // 查找当前企业
      const exterprise = exterpriseList.value.find(item => +scopeId === +item.id) // 找到当前企业
      const rant = exterprise?.rentList.find(item => id === +item.id) // 找到当前企业下的租赁记录
      rentForm.value.type = 1 // 设置操作类型，0添加，1续签
      if (rant) {
        rentForm.value.buildingId = +rant?.buildingId // 设置租赁的楼宇id
        rentForm.value.contractId = +rant.id // 设置合同id
        rentForm.value.enterpriseId = exterprise?.id // 设置企业id
        buildingName.value = rant.buildingName // 设置租赁的楼宇名称
        // 计算时间，结束时间之后再加一天
        const time = +new Date(rant.endTime) + 24 * 60 * 60 * 1000
        rentForm.value.startTime = dayjs(time).format('YYYY-MM-DD') // 续费时间

        // 保存企业id
        rentForm.value.enterpriseId = scopeId
      }
    }
  }

  const router = useRouter()
  // 关闭弹窗 -----------------
  const closeDialog = () => {
    addFormRef.value?.resetFields() // 重置表单
    timeArr.value = [] // 清空时间
    fileList.value = [] // 清空文件列表
    rentForm.value = initRentForm() // 重置表单数据

    // 如果是从工作台跳回来的，就再返回去
    if (route.query.id && route.query.scopeId) {
      router.back()
    }
  }
  // 手动关闭弹窗
  const closeManualDialog = () => {
    dialogVisible.value = false
  }

  // 表单数据默认值，每次调用，都返回一个新对象
  const initRentForm = () :RentParams => {
    return {
      buildingId: undefined, // 租赁楼宇id
      startTime: '', // 开始日期（不能小于今日日期）
      endTime: '', // 租赁结束日期
      contractUrl: '', // 合同附件url
      contractId: undefined, // 合同附件id
      type: 0, // 操作类型，添加合同0，续签合同1
      enterpriseId: undefined // 企业id
    }
  }

  // 添加合同 - 表单数据
  const rentForm = ref<RentParams>(initRentForm())

  // 添加合同 - 表单校验
  const rentRules = ref<FormRules<RentParams>>({
    buildingId: [
      { required: true, message: '请选择楼宇', trigger: 'change' }
    ],
    endTime: [
      { required: true, message: '请选择租赁日期', trigger: 'blur' }
    ],
    contractUrl: [
      { required: true, message: '请上传合同文件' }
    ]
  })

  // 添加合同 - 时间
  // 时间选择器 - 监听时间变化
  const timeArr = ref<string[]>([])

  watch(timeArr, (val) => {
    if (val) {
      rentForm.value.startTime = val[0]
      rentForm.value.endTime = val[1]
    } else {
      rentForm.value.startTime = ''
      rentForm.value.endTime = ''
    }
  }, { deep: true })
  // 通过 disabledDate 函数，来设置禁用掉的日期。
  const disabledDate = (time: Date) => {
    // 不能小于今日日期，包含今天
    return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
  }

  const addFormRef = ref<FormInstance>() // 表单实例
  const fileList = ref<UploadUserFile[]>([]) // 上传文件列表
  // 上传合同文件
  const onUploadRequest = async (options: UploadRequestOptions) => {
    // 1. 准备 FormData 对象
    const fd = new FormData()
    fd.append('file', options.file) // 文件对象
    fd.append('type', 'contract') // 租赁合同附件 contract
    // 2. 发送请求，上传文件
    const res = await uploadAPI(fd)

    // 3. 保存合同附件 url 和 id，用于添加合同
    rentForm.value.contractUrl = res.data.url
    rentForm.value.contractId = res.data.id
    // 4. 主动触发校验(如果校验通过，会清除错误信息)
    addFormRef.value?.validateField('contractUrl')
    // 5. return 后端返回的数据，保存到 response 中
    return res.data
  }

  // 删除合同文件
  const removeUpload = () => {
    // 清空数据
    rentForm.value.contractUrl = ''
    rentForm.value.contractId = undefined
    // 触发校验
    addFormRef.value?.validateField('contractUrl')
  }

  // 上传合同前，校验文件大小
  const beforeUpload = (rawFile: UploadRawFile) => {
    // size 的单位是 Byte，5M = 5 * 1024 * 1024
    const allowSize =  5 * 1024 * 1024
    // 检测文件大小
    if(rawFile.size > allowSize){
      ElMessage.error('文件过大, 请上传5M以下的文件')
      return false
    }
    return true
  }

  // 添加合同/续费合同 - 确认按钮
  const loadingFlag = ref(false)
  const addRentConfirm = async () => {
    try {
      // 校验表单
      await addFormRef.value?.validate()
      loadingFlag.value = true
      // 提交表单数据给后端
      await createRentAPI(rentForm.value)
      // 轻提示
      ElMessage.success(dialogType.value === 0 ? '添加成功' : '续费成功')
      // 重新获取合同列表
      const exterpriseFind = exterpriseList.value.find(item => item.id === rentForm.value.enterpriseId) // 找到当前企业
      onExpandChange(exterpriseFind!)
      // 关闭弹窗
      closeManualDialog()
    } finally {
      loadingFlag.value = false
    }
  }

  // 合同列表渲染----------------------------------------------------------
  const onExpandChange = async (row: EnterprisePlus) => {
    const res = await getRentListAPI(row.id) // 获取租赁列表
    row.rentList = res.data // 赋值给 row.rentList
  }

  // 退租合同
  const outRent = (row: RentItemType, scopeRow: EnterprisePlus) => {
    ElMessageBox.confirm('退租不可撤回，是否确认退租当前楼宇?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // 发送请求，更新后端合同状态
      await outRentAPI(row.id)
      // 更新前端合同状态，退租按钮变禁用
      row.status = 3
      // 轻提示
      ElMessage.success('退租成功')
      // 更新合同
      onExpandChange(scopeRow)
    }).catch(() => {
      // 点击取消，什么也不做
    })
  }

  // 删除合同（合同Row, 企业Row）
  const deleteRent = async (rentRow: RentItemType, enterPriseRow: EnterprisePlus) => {
    ElMessageBox.confirm('是否确认删除当前合同?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // 发送请求，更新后端合同状态(后端)
      await deleteRentAPI(rentRow.id)
      // 删除过滤掉合同（前端）
      enterPriseRow.rentList = enterPriseRow.rentList.filter(item => item.id !== rentRow.id)
      // 轻提示
      ElMessage.success('删除成功')
      // 更新合同
      await onExpandChange(enterPriseRow)
      // 更新企业状态
      enterPriseRow.existContractFlag = enterPriseRow.rentList.length === 0 ? 0 : 1
    }).catch(() => {
      // 点击取消，什么也不做
    })
  }

  // 设置日期范围 ---------------------------
  const disabledDateDialog = (time: any) => {
    // 获取指定日期的时间戳
    const currentTime = +new Date(rentForm.value.startTime)
    return time.getTime() < currentTime
  }
  // 设置日期展开初始值 月份要 -1
  const dateDefalt = computed(() => {
    if (!rentForm.value.startTime) return undefined
    const month = +rentForm.value?.startTime.split('-')[1]
    if (month === 1) {
      return [+rentForm.value?.startTime.split('-')[0] - 1, 12]
    } else {
      return [+rentForm.value?.startTime.split('-')[0], +rentForm.value?.startTime.split('-')[1] - 1]
    }
  })

  const route = useRoute()

  // 工作台临期合同续费跳转
  async function onRent () {
    if (route.query.id && route.query.scopeId) {
      const exterprise = exterpriseList.value.find(item => +route.query.scopeId! === +item.id) // 找到当前企业
      await onExpandChange(exterprise!) // 先给当前企业追加合同列表
      openDialog(+route.query.id, +route.query.scopeId) // 打开续费弹窗
    }
  }
</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" @clear="onSearch()" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="onSearch()">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary"  @click="$router.push('/exterpriseAdd')" v-permission="'park:enterprise:add_edit'">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="exterpriseList" @expand-change="onExpandChange" row-key="id">
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-table class="son-table" style="width: 96%;" :data="scope.row.rentList">
              <el-table-column label="租赁楼宇" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <!-- 合同的租赁状态 0待生效 1生效中 2已到期 3已退租 -->
                <template v-slot="{ row }">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-else-if="row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-else-if="row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="250">
                <template v-slot="{ row }">
                  <el-button size="small" type="text" :disabled="row.renewFlag === 0" @click="openDialog(row.id, scope.row.id)" v-permission="'park:rent:add_surrender'">续租</el-button>
                  <el-button size="small" type="text" :disabled="row.status === 3 || row.renewFlag === 0 && row.status !== 0" @click="outRent(row, scope.row)" v-permission="'park:rent:add_surrender'">退租</el-button>
                  <el-button size="small" type="text" :disabled="row.status !== 3" @click="deleteRent(row, scope.row)" v-permission="'park:rent:remove'">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作" width="350">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="openDialog(scope.row.id)" v-permission="'park:rent:add_surrender'">添加合同</el-button>
            <el-button size="small" type="primary" link @click="$router.push(`/exterpriseDetail/${scope.row.id}`)" v-permission="'park:enterprise:query'">查看</el-button>
            <el-button size="small" type="primary" link @click="$router.push(`/exterpriseAdd/${scope.row.id}`)" v-permission="'park:enterprise:add_edit'">编辑</el-button>
            <el-button size="small" type="primary" :disabled="scope.row.existContractFlag === 1" link @click="deleteEnterprise(scope.row.id)" v-permission="'park:enterprise:remove'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination 
        layout="total, sizes, prev, pager, next"
        :total="total" 
        :page-sizes="[2,5,10,20]"
        v-model:current-page="params.page" 
        v-model:page-size="params.pageSize"
        @change="getList"
      />
    </div>
    <!-- 添加合同/编辑弹窗 -->
    <el-dialog :title="dialogType === 0 ? '添加合同' : '续费合同'" v-model="dialogVisible" width="580px" @close="closeDialog()">
      <div class="form-container">
        <!-- 表单区域 -->
        <el-form ref="addFormRef" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择" v-if="dialogType === 0">
              <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-input disabled v-model="buildingName" v-else></el-input>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="endTime">
            <!-- 续费日期 -->
            <template v-if="dialogType === 1">
              <el-date-picker
                v-model="rentForm.startTime"
                type="date"
                placeholder="零基础学IT,就来黑马程序员"
                disabled
                style="width: 180px;"
              />
              <span style="padding: 0 10px;">-</span>
              <el-date-picker
                v-model="rentForm.endTime"
                type="date"
                placeholder="黑马程序员"
                style="width: 180px;"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDateDialog"
                :default-value="dateDefalt ? new Date(dateDefalt[0], dateDefalt[1]) : new Date()"
              />
            </template>
            <template v-else>
              <el-date-picker
                v-model="timeArr" 
                type="daterange" 
                range-separator="至" 
                start-placeholder="开始日期"
                end-placeholder="结束日期" 
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </template>
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractUrl">
            <el-upload
              accept=".doc, .pdf"
              :http-request="onUploadRequest"
              :limit="1"
              :before-upload="beforeUpload"
              :on-remove="removeUpload"
              v-model:file-list="fileList"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <template #tip>
                <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeManualDialog()">取 消</el-button>
        <el-button type="primary" @click="addRentConfirm()" :loading="loadingFlag">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.son-table {
  // background-color: #f4f6f8;
  margin-left: 47px;
}
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>